package com.hxd.tabactivityfragment.adapter

import android.content.Context
import android.support.v7.widget.CardView
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.hxd.tabactivityfragment.R
import com.hxd.tabactivityfragment.bean.IMPItem
import java.util.*

/**
 *  项目名：    FoodOrigins
 *  包名：      com.hxd.tabactivityfragment.adapter
 *  文件名:     HomeImpAdapter
 *  创建者:     HXD
 *  创建时间:   2019/3/13 15:11
 *  描述:       TODO
 */

class HomeImpAdapter(var dataList: ArrayList<IMPItem.Row>, var context: Context) :
    RecyclerView.Adapter<HomeImpAdapter.ViewHolder>() {

    private var mOnItemClickLitener: OnItemClickLitener? = null

    //设置回调接口
    interface OnItemClickLitener {
        fun onItemClick(view: View, position: Int, proUrl: String)
    }

    fun setOnItemClickLitener(mOnItemClickLitener: OnItemClickLitener) {
        this.mOnItemClickLitener = mOnItemClickLitener
    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view: View = LayoutInflater.from(parent.context).inflate(R.layout.item_home, parent, false)
        return ViewHolder(view)
    }

    override fun getItemCount(): Int {
        return dataList.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val data: IMPItem.Row = dataList[position]
        Glide.with(context).load(data.imgUrl).into(holder.impImage)
        holder.impName.text = dataList[position].proInfo
        //通过为条目设置点击事件触发回调
        if (mOnItemClickLitener != null) {
            holder.itemLayout.setOnClickListener { view ->
                mOnItemClickLitener!!.onItemClick(
                    view,
                    position,
                    dataList[position].proUrl
                )
            }
        }

    }

    /**
     * RecyclerView的持有者类
     */
    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        var impImage: ImageView = view.findViewById(R.id.imp_image)
        var impName: TextView = view.findViewById(R.id.imp_name)
        var itemLayout: CardView = view.findViewById(R.id.item_layout)

    }

    fun setNotifyDataSetChanged(dataList:ArrayList<IMPItem.Row>){
        this.dataList.clear()
        this.dataList = dataList
        notifyDataSetChanged()
    }

    /**
     * 设置随机打乱数据顺序
     */
    fun setRandData(){
        dataList.shuffle()
        notifyDataSetChanged()
    }

}